<script lang="ts" setup>
import { reactive, ref, watch } from "vue"
import { ElTable, ElMessageBox, FormInstance, type FormRules, ElMessage } from "element-plus"
// import { formatDateTime } from "@/utils"
import { usePagination } from "@/hooks/usePagination"
import { Search, Refresh } from "@element-plus/icons-vue"
import { useRouter } from "vue-router"
import {
  createCollectionChild,
  deleteCollectionChild,
  updateCollectionChild,
  getCollectionChild
} from "@/api/combo-h5/recommend"
import { uploadComboImageList } from "@/api/combo"
import { useCommonStore } from "@/store/modules/common"
const commonStore = useCommonStore()
const loading = ref(true)
const { paginationData, handleCurrentChange, handleSizeChange } = usePagination()
defineOptions({
  name: "childset"
})
// import { useCascaderAreaData } from "@vant/area-data"
const formData = reactive({
  packageName: "",
  packageId: "",
  heImage: "",
  // minAge: "16",
  // maxAge: "60",
  // area: eval('[["台湾省"], ["香港特别行政区"], ["澳门特别行政区"],["新疆维吾尔自治区"],["西藏自治区"],["云南省"]]'),
  sort: ""
})
// const areaoptions = useCascaderAreaData()
// const props = {
//   multiple: true,
//   checkStrictly: true,
//   label: "text",
//   value: "text"
// }
const router = useRouter()
const pid = router.currentRoute.value.query.id //套餐合集ID
const compilationId = ref<any>(undefined)
// const arrToStr = (objarr: any) => {
//   const arrLen = objarr.length
//   let row = "["
//   for (let i = 0; i < arrLen; i++) {
//     row += "["
//     for (let j = 0; j < objarr[i].length; j++) {
//       row += `'${objarr[i][j]}'`
//       if (j < objarr[i].length - 1) {
//         row += ","
//       }
//     }
//     row += "]"
//     if (i < arrLen - 1) {
//       row += ","
//     }
//   }
//   row += "]"
//   return row
// }
const handleUpdate = (row: any) => {
  compilationId.value = row.id
  formData.packageId = row.packageBackupId
  formData.sort = row.sorts
  formData.heImage = row.heImage
  // formData.maxAge = row.maxAge
  // formData.minAge = row.minAge
  // formData.area =
  //   eval(row.area) ||
  //   eval('[["台湾省"], ["香港特别行政区"], ["澳门特别行政区"],["新疆维吾尔自治区"],["西藏自治区"],["云南省"]]')
  if (row.heImage) {
    fileList.value = row.heImage?.split(",").map((item: any) => {
      return {
        url: `${commonStore.BASEURL}/image/${item}`
        // url: `http://192.168.31.143:8080/image/${item}`
      }
    })
  }
  dialogVisible.value = true
}
// #region  删
const handleDelete = (row: any) => {
  ElMessageBox.confirm(`您确定要删除:ID为${row.id}的数据吗?`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    deleteCollectionChild(row.id).then(() => {
      ElMessage.success("删除成功")
      getApplet()
    })
  })
}
// #endregion

// #region 增
const formRef = ref<FormInstance | null>(null)
const dialogVisible = ref<boolean>(false)
const rules: FormRules = reactive({
  packageId: [{ required: true, trigger: "blur", message: "请选择H5套餐" }]
  // code: [{ required: true, trigger: "blur", message: "请输入code" }]
})
/**图片上传相关 */
const fileList = ref<any>([]) /**图片列表 */
const dialogImageUrl = ref("") /**预览url  */
const dialogVisible1 = ref(false) /**预览弹窗 */
const handleChageImg = (file: any, resfileList: any) => {
  const size = ref(3)
  const fileSizeFlag = file.size / 1024 / 1024 < size.value
  if (!fileSizeFlag) {
    ElMessage.error(`请上传不大于${size.value}M的图片!`)
    fileList.value = []
  } else {
    fileList.value = resfileList
  }
}
const handlePictureCardPreview = (file: any) => {
  dialogImageUrl.value = file.url
  dialogVisible1.value = true
}
// 移除图片
const handleRemove = (file: any) => {
  const list = fileList.value
  for (const i in list) {
    if (list[i].uid === file.uid) {
      list.splice(i, 1)
    }
  }
  fileList.value = list
  formData.heImage = ""
}

const handleCreate = async () => {
  // if (fileList.value.length === 0) {
  //   ElMessage.error("请上传主图")
  //   return
  // }
  const fileData = new FormData()
  fileList.value.forEach((file: any) => {
    fileData.append("file", file.raw)
  })
  if (fileList.value.length && fileList.value[0].status === "ready") {
    await uploadComboImageList(fileData).then((res: any) => {
      if (res.code == 200) {
        formData.heImage = res.data.split("/image/")[1]
      }
    })
  }
  formRef.value?.validate((valid: boolean) => {
    if (valid) {
      if (compilationId.value === undefined) {
        createCollectionChild({
          phId: pid,
          packageBackupId: formData.packageId,
          sorts: formData.sort,
          heImage: formData.heImage
          // maxAge: formData.maxAge,
          // minAge: formData.minAge,
          // area: arrToStr(formData.area)
        }).then(() => {
          ElMessage.success("新增成功")
          dialogVisible.value = false
          getApplet()
          fileList.value = []
        })
      } else {
        updateCollectionChild({
          id: compilationId.value,
          phId: pid,
          packageBackupId: formData.packageId,
          sorts: formData.sort,
          // area: arrToStr(formData.area),
          // maxAge: formData.maxAge,
          // minAge: formData.minAge,
          heImage: formData.heImage
        }).then(() => {
          ElMessage.success("修改成功")
          dialogVisible.value = false
          getApplet()
          fileList.value = []
        })
      }
    } else {
      return false
    }
  })
}

const resetForm = () => {
  compilationId.value = undefined
  clearValidate()
  formData.packageId = ""
  formData.sort = ""
  // formData.minAge = "16"
  // formData.maxAge = "60"
  // formData.area = eval(
  //   '[["台湾省"], ["香港特别行政区"], ["澳门特别行政区"],["新疆维吾尔自治区"],["西藏自治区"],["云南省"]]'
  // )
  fileList.value = []
}
// #endregion

// #region 查
const tableTotal = ref<number>()
const tableData = ref<any>([])
const getApplet = () => {
  getCollectionChild({
    page: paginationData.currentPage,
    size: paginationData.pageSize,
    phId: pid,
    packageBackupId: searchData.packageBackupId
  })
    .then((res: any) => {
      tableData.value = res.data.list
      tableTotal.value = res.data.total
      loading.value = false
    })
    .catch(() => {
      tableData.value = []
    })
}
// #endregion

// #region 搜索内容
const searchFormRef = ref<FormInstance | null>(null)
const searchData = reactive<any>({
  packageBackupId: ""
})
const resetSearch = () => {
  searchFormRef.value?.resetFields()
  if (paginationData.currentPage === 1) {
    getApplet()
  }
  paginationData.currentPage = 1
}
const handleSearch = () => {
  if (paginationData.currentPage === 1) {
    getApplet()
  }
  paginationData.currentPage = 1
}
// #endregion
/** 监听分页参数的变化 */
watch([() => paginationData.currentPage, () => paginationData.pageSize], getApplet, { immediate: true })
const clearValidate = () => {
  formRef.value?.clearValidate()
}
import { getComboDataApi } from "@/api/combo-h5"
import { useUserStore } from "@/store/modules/user"
const userStore = useUserStore()
const comboList1 = ref<any>([])
const getH5Data = () => {
  loading.value = true
  getComboDataApi({
    page: 1,
    size: 1000,
    teamId: userStore.usernameID
  })
    .then((res) => {
      comboList1.value = res.data.list.map((item: any) => {
        if (item.anotherName) {
          return {
            id: item.id,
            name: `${item.name}_${item.anotherName}`
          }
        } else {
          return {
            id: item.id,
            name: item.name
          }
        }
      })
    })
    .catch(() => {
      comboList1.value = []
    })
    .finally(() => {
      loading.value = false
    })
}
getH5Data()
const formatterCombo = (row: any, column: any, celValue: any) => {
  comboList1.value.filter((item: any) => {
    if (item.id == row.packageBackupId) {
      celValue = item.name
    }
  })
  return celValue
}
</script>

<template>
  <div class="app-container">
    <el-card shadow="never" class="search-wrapper">
      <el-form ref="searchFormRef" :inline="true" :model="searchData">
        <el-form-item prop="packageBackupId" label="H5套餐">
          <el-select
            v-model="searchData.packageBackupId"
            clearable
            filterable
            placeholder="请选套餐,可输入快速查询"
            style="width: 300px"
            :disabled="compilationId"
          >
            <!-- :value="item.id + ''" -->
            <el-option v-for="item in comboList1" :key="item.id" :label="item.name" :value="item.id + ''" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">查询</el-button>
          <el-button :icon="Refresh" @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <!-- 中间部分 -->
    <el-card v-loading="loading" shadow="never">
      <!-- 顶部添加 -->
      <div class="middle-top">
        <div>
          <el-button type="primary" @click="dialogVisible = true">添加套餐</el-button>
        </div>
      </div>
      <!-- 中间渲染内容 -->
      <div class="table-center">
        <el-table :data="tableData">
          <el-table-column prop="id" label="ID" align="center" />
          <el-table-column prop="packageBackupId" label="H5套餐" align="center" :formatter="formatterCombo" />
          <el-table-column prop="sorts" label="排序" align="center" />
          <el-table-column fixed="right" label="操作" width="150" align="left">
            <template #default="scope">
              <p>
                <el-button type="primary" text bg size="small" @click="handleUpdate(scope.row)">修改</el-button>
              </p>
              <el-button type="danger" text bg size="small" @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 分页器 -->
      <div class="pagination">
        <el-pagination
          background
          :layout="paginationData.layout"
          :page-sizes="paginationData.pageSizes"
          :page-size="paginationData.pageSize"
          :total="tableTotal"
          :currentPage="paginationData.currentPage"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    <!-- 弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      :title="compilationId === undefined ? '新增' : '修改'"
      @close="resetForm"
      width="60%"
    >
      <el-form ref="formRef" :model="formData" :rules="rules" label-width="100px" label-position="left">
        <el-form-item prop="packageId" label="H5套餐">
          <el-select
            v-model="formData.packageId"
            clearable
            filterable
            placeholder="请选套餐,可输入快速查询"
            style="width: 100%"
            :disabled="compilationId"
          >
            <!-- :value="item.id + ''" -->
            <el-option v-for="item in comboList1" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item prop="sort" label="排序">
          <el-input v-model="formData.sort" placeholder="用合集页的排序,数字越小排名越靠前" />
        </el-form-item>
        <!-- <el-form-item prop="area" label="不发货地">
          <el-cascader
            style="width: 100%"
            size="large"
            placeholder="可输入地址快速查询"
            :props="props"
            :options="areaoptions"
            v-model="formData.area"
            :filterable="true"
          />
        </el-form-item>
        <el-form-item prop="age" label="年龄限制" class="ageInput">
          <el-input
            type="number"
            v-model="formData.minAge"
            placeholder="请输入最小年龄"
            oninput="if(value.length>2)value=value.slice(0, 2)"
          />
          <span style="display: inline-block; padding: 0 5px">至</span>
          <el-input
            type="number"
            v-model="formData.maxAge"
            placeholder="请输入最大年龄"
            oninput="if(value.length>2)value=value.slice(0, 2)"
          />
        </el-form-item> -->
        <el-form-item prop="heImage">
          <template #label>
            <span>主图</span>
            <el-tooltip class="box-item" effect="customized" placement="bottom">
              <template #content> 主图，用于产品合集页产品的主图 </template>
              <el-icon style="cursor: pointer"><InfoFilled /></el-icon>
            </el-tooltip>
          </template>
          <el-upload
            :auto-upload="false"
            :file-list="fileList"
            :show-file-list="true"
            list-type="picture-card"
            :limit="1"
            accept="image/*"
            :on-change="handleChageImg"
            :disabled="fileList.length != 0"
          >
            <el-icon><Plus /></el-icon>
            <template #file="{ file }">
              <div>
                <img class="el-upload-list__item-thumbnail" :src="file.url" />
                <span class="el-upload-list__item-actions">
                  <span class="el-upload-list__item-delete" @click="handleRemove(file)">
                    <el-icon>
                      <Delete />
                    </el-icon>
                  </span>
                  <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
                    <el-icon>
                      <zoom-in />
                    </el-icon>
                  </span>
                </span>
              </div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleCreate">确认</el-button>
      </template>
    </el-dialog>
    <el-dialog v-model="dialogVisible1">
      <img w-full :src="dialogImageUrl" alt="Preview Image" />
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
// .box-card {
//   height: 70px;
//   margin-bottom: 20px;
// }
.search-wrapper {
  margin-bottom: 20px;
}
.middle-top {
  margin-bottom: 20px;
}
.table-center {
  margin-bottom: 20px;
}
.pagination {
  display: flex;
  justify-content: flex-end;
}
.ageInput :deep(.el-input) {
  width: 20% !important;
}
</style>
